import json
from django.utils.deprecation import MiddlewareMixin
from .models import UserAction

class UserActionMiddleware(MiddlewareMixin):
    """用户行为记录中间件"""
    
    def process_response(self, request, response):
        # 只记录API请求
        if not request.path.startswith('/api/'):
            return response
            
        # 只记录已认证用户的请求
        if not request.user.is_authenticated:
            return response
            
        # 解析请求方法和路径
        method = request.method
        path = request.path
        
        # 确定操作类型
        if method == 'GET':
            action_type = 'query'
        elif method == 'POST':
            action_type = 'create'
        elif method in ['PUT', 'PATCH']:
            action_type = 'update'
        elif method == 'DELETE':
            action_type = 'delete'
        else:
            return response
            
        # 确定资源类型
        resource_type = path.split('/')[2]  # /api/resource_type/...
        
        # 获取资源ID
        try:
            resource_id = int(path.split('/')[3])
        except (IndexError, ValueError):
            resource_id = 0
            
        # 获取请求详情
        try:
            if method in ['POST', 'PUT', 'PATCH']:
                action_detail = json.loads(request.body)
            else:
                action_detail = {}
        except json.JSONDecodeError:
            action_detail = {}
            
        # 记录用户行为
        UserAction.objects.create(
            user=request.user,
            action_type=action_type,
            resource_type=resource_type,
            resource_id=resource_id,
            action_detail=action_detail
        )
        
        return response 